import React from 'react';
import { connect } from 'react-redux';
import { Form, Button, Input } from 'antd';
import { actionLogin } from '../../redux/login/login.redux.js';
import { injectIntl } from 'react-intl';
import { Prompt } from 'react-router';
import './login.css';
import axios from 'axios'
const FormItem = Form.Item;
const createForm = Form.create;
@connect(state => state.auth, {actionLogin})
class accountLogin extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            enterButton:'验证码',
            verificationCode:''
        }
    }
    componentDidMount(){
        document.addEventListener("keydown",this.handleKeydown);
        this.getCode()
    }

    removeSomeEvent=()=>{
        document.removeEventListener("keydown",this.handleKeydown);
    }
    /*验证码通过redux集成*/
    componentWillReceiveProps(nextProps){
        if(nextProps.verificationCode !== this.props.verificationCode){
            this.setState({
                verificationCode:nextProps.verificationCode
            },()=>{this.createCode(this.state.verificationCode);});
        }
    }

    /*接口调用验证码*/
    getCode=()=>{
        axios.post('/api/admin/corp/jcaptcha', {
        }).then(res => {
            if(res&&res.code==200){
                this.setState({
                    verificationCode:res.data
                },()=>{this.createCode(this.state.verificationCode)});
            }
        })
    }
    /*前端验证码样式*/
    createCode=(verificationCode)=>{
        //canvas准备中
        var $canvas = document.querySelector("#canvas");
        var ctx = $canvas.getContext('2d');
        var width = $canvas.width;
        var height = $canvas.height;
        //清空画布
        ctx.clearRect(0,0,width,height);
        //上背景色
        ctx.fillStyle="white";
        ctx.fillRect(0,0,width,height);
        ctx.fillStyle="#1890ff";
        //初始化翻转值
        var flip = 1;
        ctx.font="italic bolder 20px 'Arial'";
        //清空code
        //验证码的长度
        var codeLength = 4;
        //所有候选组成验证码的字符，当然也可以用中文的
        var codeChars = [...verificationCode]
        //在数组中任意选择6个字
        for(var i = 0; i < codeLength; i++){
            //翻转正负用于计算rotate
            flip = i%2?-1:1;
            ctx.save();
            ctx.rotate(Math.round(3*Math.random())*flip*Math.PI/180);
            ctx.fillText(codeChars[i],(width * (0.1+0.25*i)),22+Math.round(8*Math.random()));
            ctx.restore();
        }
    }
    onClick=()=>{
        this.getCode()
    }

    /*----------登陆表单处理--------------*/
    codeEqual=(rule, value, callback)=>{
        const form = this.props.form;
        const internationalization = this.props.intl.messages.newLogin;
        if (value&&value!=this.state.verificationCode) {
            callback(internationalization.tips);
        } else {
            callback();
        }
    }
    handleKeydown=(e)=>{
        e.keyCode===13&&this.userHandleSubmit(e)
    }

    userHandleSubmit= (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!!err) {
                return
            }
            this.props.actionLogin(values)
        });
    }

    render() {
        const height={
            height:40
        }

        const { getFieldDecorator } = this.props.form;
        const internationalization = this.props.intl.messages.newLogin;
        return (
                    <Form  className="login-form">
                        <FormItem>
                            {getFieldDecorator('username', {
                                rules: [
                                    { required: true, message: internationalization.usernameTips }],
                            })(
                                <Input  style={height} placeholder={internationalization.usernameTips} name={'username'}/>
                            )}
                        </FormItem>
                        <FormItem>
                            {getFieldDecorator('password', {
                                rules: [{ required: true, message: internationalization.passwordTips},
                                ],
                            })(
                                <Input style={height} type="password" placeholder={internationalization.passwordTips} name={'password'}/>
                            )}
                        </FormItem>
                        <FormItem>
                            {getFieldDecorator('verificationCode', {
                                rules: [
                                    { required: true, message: internationalization.codeTips},
                                    {validator: this.codeEqual}
                                ],
                                validateTrigger:'onBlur'
                            })(
                                <div className="verificationCode" >
                                    <Input  style={height} placeholder={internationalization.codeTips} />
                                    <canvas id="canvas" width="100" height="40" onClick={this.onClick}></canvas>
                                </div>
                            )}
                        </FormItem>
                        <FormItem>
                            <Button style={height} type="primary" onClick={this.userHandleSubmit} onKeyDown={(e)=>{this.handleKeydown(e);}} className="login-form-button">
                                {internationalization.login}
                            </Button>
                        </FormItem>
                        <a>忘记密码</a>
                        <Prompt message={this.removeSomeEvent}/>
                    </Form>
        )
    }
}
accountLogin=createForm()(accountLogin);
export default injectIntl(accountLogin);